<?php

namespace App\Controller\webSocket;

use App\Common\RedisUtils;
use App\Constants\ConstCode;
use App\Service\common\chartSwitchService;
use App\Service\common\webSocketServer;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;


class ChartWebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    use RedisUtils;

    /**
     * 服务连接
     * @param $server
     * @param $request
     * @return void
     */
    public function onOpen($server, $request): void
    {
        $message = $request->fd . ' 聊天websocket已连接' . PHP_EOL;
        echo $message;
        if (empty($request->get['token'])) {
            echo '聊天客服登录token为空,立即踢出该fd' . $request->fd;
            make(webSocketServer::class)->close($request->fd);
        } else {
            $token = $request->get['token'];
            $service = $this->getChat($token);
            if (empty($service)) {
                echo '未查询到客服登录信息,立即踢出该fd' . $request->fd;
                make(webSocketServer::class)->close($request->fd);
            } else {
                $serviceArr = json_decode($service, true);
                if (!empty($serviceArr['fd'])) {
                    $this->delChat(ConstCode::CHAT_TOKEN . $serviceArr['fd']);
                }
                $serviceArr['token'] = $token;
                $serviceArr['fd'] = $request->fd;
                $res = $this->setChat($token, json_encode($serviceArr, 256), 5 * 3600);//心跳为60秒
                if ($res) {
                    $this->setChat(ConstCode::CHAT_TOKEN . $request->fd, json_encode($serviceArr, 256), 300);//心跳为60秒
                } else {
                    echo '未存储客服登录信息,立即踢出该fd' . $request->fd;
                    make(webSocketServer::class)->close($request->fd);
                }
            }
        }
        $pushData['accessType'] = 'connect';
        $pushData['data']['msg'] = $message;
        $server->push($request->fd, json_encode($pushData, 256));
    }

    /**
     * 接受消息
     * @param $server
     * @param $frame
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function onMessage($server, $frame): void
    {
        $result = make(chartSwitchService::class)->getChartSwitchService($frame->fd, $frame->data);
        var_dump('----------------------------');
        var_dump($frame->fd . ' 发送测试数据数据 ' . $frame->data);
//        echo '发给 ' . $frame->fd . ' 号客户端的消息：' . $frame->data;
        //    $server->push($frame->fd, $frame->data);
    }

    /**
     * 服务关闭
     * @param $server
     * @param int $fd
     * @param int $reactorId
     * @return void
     */
    public function onClose($server, int $fd, int $reactorId): void
    {
        $message = $fd . '断开连接,处理线程是 ' . $reactorId . PHP_EOL;
        echo $message;
    }
}